// pages/shopcart/index.js
import {getSetting,chooseAddress,openSetting,showModal,showToast} from"../../utils/asyncWx.js"
Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    cart:[],
    allChecked:false,
    totalPrice:0,
    totalNum:0

  },
  /*getUserAdress(){
    wx.getSetting({
      complete: (res) => {
        const scopeAddress=res.authSetting["scope.address"];
        if(scopeAddress===true||scopeAddress===undefined){
          wx.chooseAddress({
            complete: (res1) => { 
              console.log(res1);
            },
          })

        }else{
          wx.openSetting({
            
            success: (result) => { wx.chooseAddress({
              complete: (res1) => { 
                console.log(res1);
              },
            })},
          })
        }
      },
    })
  },*/

  async getUserAdress(){
    const res1=await getSetting();
    //判断是否有获取地址权限,有权限正常调用api，无权限引导用户打开设置页面授予权限
    const scopeAddress=res1.authSetting["scope.address"];
    try{
       if(scopeAddress===false){
         await openSetting(); 
          }      
     const res2=await chooseAddress();
     wx.setStorageSync('address', res2)
    }catch(error)
    {
      console.log(error);
    }

  },

 //勾选checkbox改变checked值
  handleItemChange(e){
    const goods_id=e.currentTarget.dataset.index;
    let cart=this.data.cart;
    let index=cart.findIndex(v=>v.goods_id===goods_id);
    cart[index].checked=!cart[index].checked;
    this.setCart(cart);
  },

  setCart(cart){
    /*const allChecked=cart.length?cart.every(v=>v.checked):false;*/
    let totalPrice=0;
    let totalNum=0;
    let allChecked=true;
    cart.forEach(v=>{
      if(v.checked)
      {
        totalPrice+=v.goods_price*v.num;//设置GoodsInfo原因之一，有具体的数据
        totalNum+=v.num;
      }
      else{
        allChecked=false;
      }
    })
    allChecked=cart.length!=0?allChecked:false;
    this.setData({   
      cart:cart,
      allChecked:allChecked,
      totalNum:totalNum,
      totalPrice:totalPrice
    });
    wx.setStorageSync('cart', cart);

  },

  handleItemAllChecked(){
    let allChecked=this.data.allChecked;
    let cart=this.data.cart;
    allChecked=!allChecked;
    cart.forEach(v=>v.checked=allChecked);
    this.setCart(cart);
  },

  //设置数量小于1时，询问用户删除或取消
  async handleItemNum(e){  
    const {operation,id}=e.currentTarget.dataset;
    let {cart}=this.data;
    const index=cart.findIndex(v=>v.goods_id===id);
    if(cart[index].num===1&&operation===-1){
    
      /*wx.showModal({
        title: '提示',
        content: '是否要删除？',
        success :(res)=> {
        if (res.confirm) {
        cart.splice(index,1);
        this.setCart(cart);
        } else if (res.cancel) {
        console.log('用户点击取消')
        }
      }
    })*/

    const res=await showModal({content:'是否要删除？'});
    if (res.confirm) {
      //移除购物车
      cart.splice(index,1);
      this.setCart(cart);
      } 
    }else{    
       cart[index].num+=operation;
       this.setCart(cart);
     }
},

async handlePay(){
   const {address,totalNum}=this.data;
   if(!address.userName){
     await showToast({title:'您还没有选择收货地址'});
     return;
   }
   if(totalNum===0){
    await showToast({title:'您还没有选择商品'});
    return;
   }
   wx.navigateTo({
     url: '/pages/pay/index',
   })

},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const address=wx.getStorageSync("address");
    const cart=wx.getStorageSync('cart')||[];
   
    this.setData({address});
    this.setCart(cart);

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})